<template>
    <div class="edit-popup">
        <popup
            ref="popupRef"
            :title="popupTitle"
            :async="true"
            width="550px"
            @confirm="handleSubmit"
            @close="handleClose"
        >
            <el-form
                class="ls-form"
                ref="formRef"
                :rules="rules"
                :model="formData"
                label-width="84px"
            >
                <el-form-item label="相册名称" prop="title">
                    <el-input v-model="formData.title" placeholder="请输入相册名称" />
                </el-form-item>
                <el-form-item label="相册封面" prop="image">
                    <el-upload
                        class="avatar-uploader"
                        :action="upLoadUrl"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload"
                    >
                        <img v-if="formData.image" :src="formData.image" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                    </el-upload>
                    
                </el-form-item>
            </el-form>
        </popup>
    </div>
</template>
<script lang="ts" setup>
import type { FormInstance, UploadProps } from 'element-plus'
import { apiPhotoAdd, apiPhotoEdit } from '@/api/album';
import Popup from '@/components/popup/index.vue'
import { ref, reactive, computed, shallowRef, defineProps, toRaw } from 'vue'
import feedback from '@/utils/feedback'

const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑相册照片' : '新增相册照片'
})

const albumId = ref()

const formData = reactive({
    mu_id: '',
    album_id: '',
    title: '',
    image: '',
})

const rules = {
    title: [
        {
            required: true,
            message: '请输入照片标题',
            trigger: ['blur']
        }
    ],
    image: [
        {
            required: true,
            message: '请上传照片',
            trigger: ['blur']
        }
    ]
}

const handleSubmit = async () => {
    await formRef.value?.validate()
    mode.value == 'edit' ? await apiPhotoEdit({...formData, id: albumId.value}) : await apiPhotoAdd(formData)
    popupRef.value?.close()
    emit('success')
}

const handleClose = () => {
    emit('close')
}

const open = (type = 'add') => {
    mode.value = type
    popupRef.value?.open()
}

const setFormData = (data: Record<any, any>) => {
    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
    }
    if(data.id){
        albumId.value = data.id
    }
}
// 相册封面
    // 上传图片
const upLoadUrl = import.meta.env.VITE_APP_BASE_URL + '/api/upload/image'
const imageUrl = ref('')
const handleAvatarSuccess: UploadProps['onSuccess'] = ( response, uploadFile ) => {
    console.log(response, toRaw(uploadFile))
    // formData.image = URL.createObjectURL(uploadFile.raw!)
    formData.image = response.data.uri
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
        feedback.msgError('上传图片只能是 JPG 格式 或 png 格式!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        feedback.msgError('上传图片大小不能超过 2MB!')
        return false
    }
    return true
}

defineExpose({
    open,
    setFormData
})
</script>
<style scoped>
    .avatar-uploader{
        border: 1px dashed #cdd0d6;
        border-radius: 6px;
        overflow: hidden;
        width: 100px;
        height: 100px;
        box-sizing: border-box;
    }
    .avatar-uploader .avatar {
        width: 100px;
        height: 100px;
        display: block;
    }

    .avatar-uploader .el-upload {
        border: 1px dashed var(--el-border-color);
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: var(--el-transition-duration-fast);
    }

    .avatar-uploader .el-upload:hover {
        border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 100px;
        height: 100px;
        text-align: center;
    }
</style>
